const fs = require('fs')
const nodeUtil = require('util');
const util = require('../util')
const config = require('../config')

const logger = util.getLogger('task.shell')
const writeFile = nodeUtil.promisify(fs.writeFile);   //写文件

const run = async (jobGroup, jobId) => {
  let filePath = `${config.upload.publishDir}/tmp/shell-${jobId}-${jobGroup.id}.sh`
  //配置主鹰爪如果不存在，就把mongodb中保存的配置写入文件，如果已存在，使用现有文件即可
  // if (! (await util.exists(filePath))) {
  //   logger.debug('shell文件不存在，重新创建:\n', jobGroup.file)
  //   await writeFile(filePath, jobGroup.file)
  // }
  //每次都重新创建
  await writeFile(filePath, jobGroup.file)
  let commond = `chmod +x ${filePath}`
  logger.info(`运行授权命令: ${commond}`)
  let out = await util.runExec(commond)
  logger.debug(`授权命令 ${commond} ，输出：`, out)
  //默认超时时间为10分钟
  out = await util.runShellFile(filePath, undefined, Object.assign({timeout: 600000}, jobGroup.options))
  return out
}

//删除任务，空函数
const remove = (jobGroup, jobId) => {
}

// 向livy提交 spark 任务，并定时查询运行状态与日志
module.exports = {
  run, remove
}